const webpack = require('webpack')
const path = require('path')
const commonConfig = require('./webpack.common')
const { merge } = require('webpack-merge')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin') // 压缩输出的css代码
const TerserWebpackPlugin = require('terser-webpack-plugin')

module.exports = merge(commonConfig, {
  mode: 'production', // 生产模式下会自动启用tree shaking, 是一组优化配置
  devtool: 'nosources-source-map',
  output: {
    filename: 'js/[name]-[contenthash:8].js', // 占位符[]
    path: path.join(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.less$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'] //生成css文件，通过link注入html中
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader']
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
      filename: 'index.html',
      favicon: './public/favicon.ico',
      // chunks: [] // 多入口打包时，在html中指定注入的bundle.js
    }),
    new webpack.DefinePlugin({ // 为代码注入全局成员,值为符合js语句的代码片断
      BASE_URL: process.env.NODE_ENV
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name]-[contenthash:8].css'
    }),
    // new OptimizeCSSAssetsPlugin(),
    new CleanWebpackPlugin(), // 自动将打包结果清除
    // new CopyWebpackPlugin(['public']),
  ],
  optimization: {
    concatenateModules: true, // 尽可能合并模块，减少代码体积，提升效率
    sideEffects: true, // 开启副作用检查，有副作用的文件不去除
    splitChunks:{ // 提供共同的模块到公共的bundler当中
      chunks: 'all'
    },
    usedExports:  true, // 标记枯树叶、枝
    minimize: true, // 去除枯树叶、枝. 开启minimizer的配置生效，自定义文件压缩器
    minimizer: [
      new OptimizeCSSAssetsPlugin(),
      new TerserWebpackPlugin() // 不开启minimize，自动开启内置js压缩器压缩
    ]
  }
})